package com.codeoss.framework.expression;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Service;

@Service
public class SpringELScriptService implements IScriptService,ApplicationContextAware{
    private ApplicationContext applicationContext;
	@Override
	public <T extends Object> T eval(String script, Map<String, Object> bindingMap) {
		// TODO Auto-generated method stub

		StandardEvaluationContext context = new StandardEvaluationContext(new Object());
		if(bindingMap!=null) {
			context.setVariables(bindingMap);
		}
		context.setBeanResolver(new BeanFactoryResolver(applicationContext));
		ExpressionParser parser = new SpelExpressionParser();
		// Object
		// value=parser.parseExpression("@loginService.login(null)").getValue(context);
		Object value = parser.parseExpression(script).getValue(context);
		return (T)value;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		// TODO Auto-generated method stub
		this.applicationContext=applicationContext;
	}
}
